# coding:utf-8
from django.shortcuts import render, HttpResponseRedirect, HttpResponse
import models
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from forms import ArticleForm
# Create your views here.


def index(request):
    articles = models.Article.objects.all()
    return render(request, 'index.html', {'articles': articles})


def category(request, category_id):
    articles = models.Article.objects.filter(category_id=category_id)
    return render(request, 'index.html', {'articles': articles})

@login_required
def article_detail(request, article_id):
    try:
        article_obj = models.Article.objects.get(id=article_id)
    except ObjectDoesNotExist as e:
        return render(request, '404.html', {'error_msg': u'文章不存在'})
    return render(request, 'article.html', {'article_obj': article_obj})


def acc_logout(request):
    logout(request)
    return HttpResponseRedirect('/account/login/')


def acc_login(request):
    err_msg = ""
    do_next = request.GET.get('next') or None
    print request.GET
    print request.POST
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            print request.GET
            return HttpResponseRedirect(do_next or '/')
        else:
            err_msg = "Wrong username or password!"
    return render(request, 'login.html', {'err_msg': err_msg, 'next': do_next})


def new_article(request):
    if request.method == 'POST':
        print request.POST
        form = ArticleForm(request.POST,request.FILES)
        if form.is_valid():
            print form.cleaned_data
            form_data = form.cleaned_data
            form_data['author_id'] = request.user.userprofile.id
            new_article_obj = models.Article(**form_data)
            new_article_obj.save()
            return render(request, 'new_article.html', {'new_article_obj': new_article_obj})
        else:
            print form.errors
    category_list = models.Category.objects.all()
    return render(request, 'new_article.html', {'category_list': category_list})


def comment(request):
    print request.POST
    if request.method == 'POST':
        new_comment_obj = models.Comment(
            article_id = request.POST.get('article_id'),
            parent_comment_id = request.POST.get('parent_comment_id') or None,
            # comment_type = request.POST.get('comment_type'),
            user_id = request.user.userprofile.id,
            comment = request.POST.get('comment')
        )
        new_comment_obj.save()
    return HttpResponse("post-comment-success")
